package a07_二叉树;

/**
 * <p>
 * a18_从中序与后序遍历序列构造二叉树复习0
 * </p>
 *
 * @author flyduck
 * @since 2025/1/8
 */
public class a18_从中序与后序遍历序列构造二叉树复习0 {
    //inorder = [9,3,15,20,7],  左中右
    //postorder = [9,15,7,20,3] 左右中
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if (inorder.length == 0) {
            return null;
        }
        //找出中
        int rootVal = postorder[postorder.length - 1];
        TreeNode rootNode = new TreeNode(rootVal);

        //找出中的位置
        int rootIdx = 0;
        for (int i = 0; i < inorder.length; i++) {
            if(inorder[i] == rootVal){
                rootIdx = i;
            }
        }

        int[] leftInorder = splitArray(inorder, 0, rootIdx - 1);
        int[] rightInorder = splitArray(inorder, rootIdx + 1, inorder.length - 1);

        int[] leftPostorder = splitArray(postorder, 0, leftInorder.length - 1);
        int[] rightPostorder = splitArray(postorder, leftInorder.length, postorder.length - 2);
        rootNode.left = buildTree(leftInorder, leftPostorder);
        rootNode.right = buildTree(rightInorder, rightPostorder);
        return rootNode;
    }


    private int[] splitArray(int[] array,int leftIdx,int rightIdx){
        int[] result = new int[rightIdx - leftIdx + 1];
        for (int i = 0; i < result.length; i++) {
            result[i] = array[leftIdx];
            leftIdx++;
        }
        return result;
    }
}
